import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/jiance/editresult.dart';
import 'package:magic_car/jiance/inspectresults.dart';
import 'package:magic_car/jiance/inspectstart.dart';
import 'package:magic_car/jiance/papularInspects.dart';
import 'package:magic_car/jiance/start.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/services.dart';


class PriceDiffrentPage extends StatefulWidget {
  final String oid;
  PriceDiffrentPage(this.oid);
  State<StatefulWidget> createState() {
    return new DetailState(this.oid);
  }
}

class DetailState extends State<PriceDiffrentPage> {
  final String oid;
  DetailState(this.oid);
  List formList;
  Map order_info = new Map();
  String price = "0.00";
  String status = "订单状态";
  String order_sn = "订单编号";
  String handelStr = "开始检测";
  String statuscode = "0";
  String income = "0.00";
  String peifu = "0.00";
  String oldprice = '0.00';
  List imgs = ['resource/images/user/upimg.png'];
  TextEditingController priceController = new TextEditingController();
  initState() {
    super.initState();
    formList = [
      {
        "title": '预约项目',
        'sub_title': '预约项目',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '联系人',
        'sub_title': '联系人',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '联系电话',
        'sub_title': '联系电话',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '预约时间',
        'sub_title': '预约时间',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '品牌',
        'sub_title': '品牌',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '预约车型',
        'sub_title': '预约车型',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '车价',
        'sub_title': '车价',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      {
        "title": '下单时间',
        'sub_title': '下单时间',
        'sub_color': Color.fromRGBO(27, 182, 251, 1)
      },
      // {
      //   "title": '担责',
      //   'sub_title': '下单时间',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1)
      // },
      // {
      //   "title": '下单时间',
      //   'sub_title': '下单时间',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1)
      // },
    ];
    loadOrderInfo();
  }

  confirm() async {
    FocusScope.of(context).requestFocus(FocusNode()); //隐藏键盘
    if(priceController.text.length==0){
       Toast.show('请输入正确的金额', context);
       return;
    }
    else if (priceController.text[0] == "0") {
      Toast.show('请输入正确的金额', context);
      return;
    } else if (double.parse(priceController.text) < 1) {
      Toast.show('充值金额必须大于1', context);
      return;
    } 
    if(imgs.length==1){
      Toast.show('请上传图片', context);
      return;
    }

    var image_Str = "";
    for(var i=0;i<imgs.length;i++ ){
      var item = imgs[i];
      if(i==imgs.length-1){
       image_Str=image_Str+item;
      }else
       image_Str=image_Str+item+',';
    }

    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    
    map['img']=image_Str;

    map['money']=priceController.text;

    // map["type"]="0";

    HttpHelper.post(HttpHelper.API_Changeprice, (data) async {
      if (data != null) {
        print(data);
        Toast.show(data['msg'], context);
        if (data['code'].toString() == '1') {
         Navigator.of(context).pop();
        }else{
          
        }
      }
    }, params: map);
  }

  //加载订单信息
  loadOrderInfo() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    //  SharedPreferences pref = await SharedPreferences.getInstance();
    //  map["id"]=pref.getString('uid');
    //  map["type"]="0";

    HttpHelper.post(HttpHelper.API_OrderDetail, (data) async {
      if (data != null) {
        if (data["code"].toString() == "1") {
          List oldlist = formList;
          var orderinfo = data["info"];
          for (var i = 0; i < oldlist.length; i++) {
            var item = oldlist[i];
            var str = "";
            if (i == 0)
              str = orderinfo["test_type"];
            else if (i == 1)
              str = orderinfo["name"];
            else if (i == 2)
              str = orderinfo["phone_num"];
            else if (i == 3)
              str = orderinfo["add_time"];
            else if (i == 4)
              str = orderinfo["brand_string"]["name"];
            else if (i == 5)
              str = orderinfo["cartype_string"]["name"];
            else if (i == 6)
              str = orderinfo["brand_string"]["name"];
            else if (i == 7) str = orderinfo["order_time"];

            item["sub_title"] = str;
          }
          String tempStr = "";
          String statu = data["info"]["status"];
          if (statu == "0") {
            tempStr = "待处理";
          } else if (statu == "1") {
            tempStr = "进行中";
            handelStr = "继续检测";
          } else if (statu == "2") {
            tempStr = "待评价";
            handelStr = "查看结果";
          } else {
            tempStr = "已完成";
            handelStr = "查看结果";
          }

          if (data["info"]["is_accept"] != '1') {
            handelStr = "确认订单";
          }
          setState(() {
            handelStr = handelStr;
            formList = oldlist;
            order_info = data["info"];
            price = data["info"]["orderPrice"];
            oldprice = data["info"]["orderPrice"];
            status = tempStr;
            order_sn = data["info"]["order_sn"];
            statuscode = statu;
            income = data['info'].containsKey('income_arr')
                ? data['info']['income_arr']['inspector'].toString()
                : '0.00';
            peifu = data['info'].containsKey('peifu_arr')
                ? data['info']['peifu_arr']['inspector'].toString()
                : '0.00';
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            '订单金额异常',
            style: TextStyle(color: Colors.white),
          ),
          backgroundColor:Colours.app_main,
          elevation: 0,
          iconTheme: new IconThemeData(color: Colors.white),
        ),
        body: Container(
          child: new ListView(
            children: <Widget>[
              Container(
                height: 150,
                color: Colours.app_main,
                child: Padding(
                  padding: new EdgeInsets.fromLTRB(15, 20, 15, 10),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: new EdgeInsets.all(10),
                        child: Text(
                          '订单编号：' + order_sn,
                          style: TextStyle(fontSize: 13, color: Colors.white),
                        ),
                      ),
                      Padding(
                        padding: new EdgeInsets.all(10),
                        child: Text(
                          '订单金额：' + oldprice,
                          style: TextStyle(fontSize: 18, color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Container(
                height: 10,
                color: Color.fromRGBO(238, 238, 238, 1),
              ),
              Padding(
                padding: new EdgeInsets.fromLTRB(35, 10, 35, 0),
                child: TextField(
                  controller: priceController,
                  inputFormatters: [
                    WhitelistingTextInputFormatter(RegExp("[0-9]")), //只允许输入字母
                  ],
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                      focusedBorder: OutlineInputBorder(
                        borderSide:
                            BorderSide(color: Color.fromRGBO(33, 192, 193, 1)),
                      ),
                      labelText: '请输入差价',
                      labelStyle: TextStyle(color: Colors.grey),
                      contentPadding: EdgeInsets.all(10.0),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
//            borderSide: BorderSide(color: Colors.red, width: 3.0, style: BorderStyle.solid)//没什么卵效果
                      )),
                ),
              ),
              Padding(
                padding: new EdgeInsets.fromLTRB(35, 10, 35, 0),
                child: Text('补充相应图片'),
              ),
              Padding(
                padding: new EdgeInsets.fromLTRB(25, 10, 25, 0),
                child: Imgs(),
              ),
              Padding(
                padding: new EdgeInsets.fromLTRB(35, 20, 35, 20),
                child: SizedBox(
                    width: double.infinity,
                    height: 50,
                    child: new RaisedButton.icon(
                      icon: new Image.asset('resource/images/user/answer.png'),
                      label: Text(
                        '确定改价',
                        style: TextStyle(fontSize: 15),
                      ),
                      color: Colours.app_main,
                      textColor: Colors.white,
                      onPressed: () {
                        confirm();
                      },
                    )),
              )
            ],
          ),
        ));
  }

  //漆膜仪检测的数值
  Widget Imgs() {
    Widget content;
    List<Widget> tiles = [];

    for (int i = 0; i < imgs.length; i++) {
      if (i == imgs.length - 1) {
        tiles.add(GestureDetector(
            onTap: () {
              showimgAlert(1, i);
            },
            child: Image.asset('resource/images/user/upimg.png',
                width: 100, height: 100)));
      } else {
        tiles.add(GestureDetector(
            onTap: () {
              showimgAlert(2, i);
            },
            child: CachedNetworkImage(
              imageUrl: imgs[i],
              width: 100,
              height: 100,
            )));
      }
    }

    content = new Wrap(spacing: 5, runSpacing: 5, children: tiles);
    return content;
  }

  //弹出相册方式
  showimgAlert(type, index) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: type == 2 ? 170 : 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('上传图片', style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            uploadImgs(1);
                          },
                          child: Center(
                              child: Text('相机',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            uploadImgs(2);
                          },
                          child: Center(
                              child:
                                  Text('相册', style: TextStyle(fontSize: 16))))),
                  type == 2
                      ? new Container(
                          height: 40,
                          child: new GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                Navigator.pop(context);
                                imgs.removeAt(index);
                                setState(() {
                                  imgs = imgs;
                                });
                              },
                              child: Center(
                                  child: Text('删除',
                                      style: TextStyle(fontSize: 16)))))
                      : new Container(height: 0),
                ]),
              ));
        });
  }

  //上传图片
  uploadImgs(type) async {
    var image;

    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    }
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      // print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        imgs.insert(0, data['url']);
        setState(() {
          imgs = imgs;
        });
        //Imgs();

      }
    }, params: map);
  }
}
